package com.xxxy.hyc.xyxmp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.textfield.TextInputEditText;
import com.xxxy.hyc.xyxmp.R;
import com.xxxy.hyc.xyxmp.bean.User;
import com.xxxy.hyc.xyxmp.utils.UserSessionManager;

import java.util.Random;

public class LoginActivity extends AppCompatActivity {

    private TextInputEditText etPhone, etVerificationCode;
    private Button btnSendCode, btnLogin;
    private String verificationCode = "";
    private CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initViews();
        setListeners();
    }

    private void initViews() {
        etPhone = findViewById(R.id.et_phone);
        etVerificationCode = findViewById(R.id.et_verification_code);
        btnSendCode = findViewById(R.id.btn_send_code);
        btnLogin = findViewById(R.id.btn_login);
    }

    private void setListeners() {
        btnSendCode.setOnClickListener(v -> sendVerificationCode());
        btnLogin.setOnClickListener(v -> login());
    }

    private void sendVerificationCode() {
        String phone = etPhone.getText().toString().trim();
        
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (phone.length() != 11) {
            Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 生成6位随机验证码
        Random random = new Random();
        StringBuilder codeBuilder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            codeBuilder.append(random.nextInt(10));
        }
        verificationCode = codeBuilder.toString();
        
        // 显示验证码（实际应用中应该通过短信发送）
        Toast.makeText(this, "验证码已发送（测试环境：验证码为 " + verificationCode + "）", Toast.LENGTH_LONG).show();
        
        // 启动倒计时
        startCountdown();
    }

    private void startCountdown() {
        btnSendCode.setEnabled(false);
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                btnSendCode.setText("重新发送(" + (millisUntilFinished / 1000) + "s)");
            }

            @Override
            public void onFinish() {
                btnSendCode.setEnabled(true);
                btnSendCode.setText("发送验证码");
            }
        }.start();
    }

    private void login() {
        String phone = etPhone.getText().toString().trim();
        String code = etVerificationCode.getText().toString().trim();
        
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (phone.length() != 11) {
            Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (!code.equals(verificationCode)) {
            Toast.makeText(this, "验证码错误", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 登录成功，保存用户信息
        User currentUser = new User();
        currentUser.setPhone(phone);
        UserSessionManager.getInstance().login(currentUser);
        
        // 实际应用中这里应该跳转到主页面
        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
        
        // 跳转到主页面
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}